/*pipedemo.c*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h> // 补充头文件

char sendbuf[] = "I am linux";
char recbuf[20];
char parrecbuf[20];

void reverse(char *str1) { 
    if (str1 == NULL) return;
    char* p = str1;
    char* q = str1;
    while (*q) ++q;
    q--;
    while (q > p) {
        char t = *p;
        *p++ = *q;
        *q-- = t;
    }
}

int main() {
    int mypipe[2], fd;
    if (pipe(mypipe) < 0) { 
        perror("pipe failed"); 
        exit(EXIT_FAILURE); 
    }
    if ((fd = fork()) < 0) { 
        perror("fork failed"); 
        exit(EXIT_FAILURE); 
    }

    if (fd == 0) { // 子进程
        close(mypipe[1]); // 关闭用不到的写端
        ssize_t read_len = read(mypipe[0], recbuf, sizeof(recbuf) - 1); // 安全读取
        if (read_len < 0) {
            perror("child read failed");
            exit(EXIT_FAILURE);
        }
        recbuf[read_len] = '\0'; // 确保字符串终止
        printf("The child process get %s\n", recbuf);
        reverse(recbuf);
        write(mypipe[1], recbuf, strlen(recbuf)); // 写入倒序数据
        close(mypipe[0]); // 关闭读端
    } else { // 父进程
        close(mypipe[0]); // 关闭用不到的读端
        write(mypipe[1], sendbuf, strlen(sendbuf));
        close(mypipe[1]); // 关闭写端
        wait(NULL); // 等待子进程结束
        ssize_t par_read_len = read(mypipe[0], parrecbuf, sizeof(parrecbuf) - 1);
        if (par_read_len < 0) {
            perror("parent read failed");
            exit(EXIT_FAILURE);
        }
        parrecbuf[par_read_len] = '\0'; // 处理读取数据
        printf("The parent process get %s\n", parrecbuf);
        close(mypipe[0]); // 关闭读端
    }
    return 0;
}
